package com.app.service.impl;

import cn.hutool.core.util.StrUtil;
import com.app.annotion.RedisLockAnnotation;
import com.app.common.Result;
import com.app.mapper.*;
import com.app.model.*;
import com.app.service.AdminUserService;
import com.app.service.IDividedIntoRecordService;
import com.app.service.IntegralOrderService;
import com.app.utils.CommonHelp;
import com.app.utils.StringTool;
import com.app.vo.IntegralOrderVo;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.query.MPJQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.Timestamp;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 积分订单
 *
 * @author 16693103420
 * @since 2024-02-01
 */
@Service
public class IntegralOrderServiceImpl extends ServiceImpl<IntegralOrderMapper, IntegralOrderModel> implements IntegralOrderService {
    @Autowired
    private IntegralOrderMapper integralOrderMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private IntegralGoodsMapper integralGoodsMapper;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private InviteRecordMapper inviteRecordMapper;
    @Autowired
    private InviteConfigMapper inviteConfigMapper;
    @Autowired
    private IntegralRecordMapper integralRecordMapper;
    @Autowired
    private VoucherRecordMapper voucherRecordMapper;
    @Autowired
    private MessageBoxMapper messageBoxMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IDividedIntoRecordService dividedIntoRecordService;

    @Autowired
    private AdminUserService adminUserService;

    @Override
    public IntegralOrderVo getIntegralOrderList(Integer page, Integer limit, String goodsName, Integer status, String areaId, String phone) {
        Page<IntegralOrderModel> page1 = new Page<>(page, limit);

        MPJQueryWrapper<IntegralOrderModel> qw = new MPJQueryWrapper<>();
        qw.selectAll(IntegralOrderModel.class);
        qw.select("ta.area", "tc.city", "tp.province");
        qw.leftJoin("tbc_areas ta on t.area_id = ta.area_id");
        qw.leftJoin("tbc_cities tc on ta.city_id = tc.city_id");
        qw.leftJoin("tbc_provinces tp on tc.province_id = tp.province_id");
        qw.leftJoin("tb_user tu on tu.id = t.user_id").like(StrUtil.isNotBlank(phone), "tu.phone", phone);
        if (StrUtil.isNotBlank(areaId)) {
            qw.eq("t.area_id", areaId);
        }
        if (StrUtil.isNotBlank(goodsName)) {
            qw.like("t.goods_name", goodsName);
        }
        if (status != null) {
            qw.eq("t.status", status);
        }
        qw.orderByDesc("t.create_time");
        Page<IntegralOrderModel> integralOrderPage = integralOrderMapper.selectPage(page1, qw);
        List<IntegralOrderModel> integralOrderList = integralOrderPage.getRecords();
        for (IntegralOrderModel integralOrder : integralOrderList) {
            integralOrder.setAreaText(integralOrder.getProvince() + "/" + integralOrder.getCity() + "/" + integralOrder.getArea());
            Integer orderStatus = integralOrder.getStatus();
            if (orderStatus == 1) {
                integralOrder.setStatusText("待发货");
            }
            if (orderStatus == 2) {
                integralOrder.setStatusText("待收货");
            }
            if (orderStatus == 3) {
                integralOrder.setStatusText("已完成");
            }
            if (integralOrder.getUserId() != null) {
                UserModel userModel = userService.getById(integralOrder.getUserId());
                integralOrder.setUser(userModel);
            }
            Integer goodsId = integralOrder.getGoodsId();
            if (goodsId != null) {
                GoodsModel goodsModel = goodsMapper.selectById(goodsId);
                integralOrder.setGoods(goodsModel);
            }
            Integer integralGoodsId = integralOrder.getIntegralGoodsId();
            if (integralGoodsId != null) {
                IntegralGoodsModel integralGoodsModel = integralGoodsMapper.selectById(integralGoodsId);
                integralOrder.setIntegralGoods(integralGoodsModel);
            }
        }
        long count = integralOrderPage.getTotal();
        IntegralOrderVo integralOrderVo = new IntegralOrderVo();
        integralOrderVo.setList(integralOrderList);
        integralOrderVo.setCount((int) count);
        return integralOrderVo;
    }

    @Override
    public IntegralOrderVo getUserIntegralOrderList(Integer page, Integer limit, String goodsName, Integer status, Integer userId) {
        Page<IntegralOrderModel> page1 = new Page<>(page, limit);
        QueryWrapper<IntegralOrderModel> qw = new QueryWrapper<>();
        if (StringTool.isNotEmpty(goodsName)) {
            qw.like("goods_name", goodsName);
        }
        if (status != null) {
            qw.eq("status", status);
        }
        if (userId != null) {
            qw.eq("user_id", userId);
        }
        qw.orderByDesc("create_time");
        Page<IntegralOrderModel> integralOrderPage = integralOrderMapper.selectPage(page1, qw);
        List<IntegralOrderModel> integralOrderList = integralOrderPage.getRecords();
        for (IntegralOrderModel integralOrder : integralOrderList) {
            Integer orderStatus = integralOrder.getStatus();
            if (orderStatus == 1) {
                integralOrder.setStatusText("待发货");
            }
            if (orderStatus == 2) {
                integralOrder.setStatusText("待收货");
            }
            if (orderStatus == 3) {
                integralOrder.setStatusText("已完成");
            }

            Integer goodsId = integralOrder.getGoodsId();
            if (goodsId != null) {
                GoodsModel goodsModel = goodsMapper.selectById(goodsId);
                integralOrder.setGoods(goodsModel);
            }
            Integer integralGoodsId = integralOrder.getIntegralGoodsId();
            if (integralGoodsId != null) {
                IntegralGoodsModel integralGoodsModel = integralGoodsMapper.selectById(integralGoodsId);
                integralOrder.setIntegralGoods(integralGoodsModel);
            }
        }
        long count = integralOrderPage.getTotal();
        IntegralOrderVo integralOrderVo = new IntegralOrderVo();
        integralOrderVo.setList(integralOrderList);
        integralOrderVo.setCount((int) count);
        return integralOrderVo;
    }



    @Override
    public boolean confirmReceipt(String orderSn) {
        try {
            List<InviteConfigModel> inviteConfigModels = inviteConfigMapper.selectList(null);
            QueryWrapper<IntegralOrderModel> integralOrderModelQueryWrapper = new QueryWrapper<>();
            integralOrderModelQueryWrapper.eq("order_sn", orderSn);
            IntegralOrderModel orderModel = integralOrderMapper.selectOne(integralOrderModelQueryWrapper);
            if (orderModel != null) {
                orderModel.setStatus(3);
                //获取返佣比例
                Double brokerage = inviteConfigModels.get(0).getBrokerage();
                Double brokerageTwo = inviteConfigModels.get(0).getBrokerageTwo();
                orderModel.setBrokerage(brokerage);
                orderModel.setBrokerageTwo(brokerageTwo);
                //分佣积分
                Double voucher = orderModel.getVoucher();//消费的券
                double v = voucher * inviteConfigModels.get(0).getConversion();//根据比例转换的积分
                double fist = v * brokerage;
                double second = v * brokerageTwo;
                orderModel.setFirstBrokerageFee(fist);
                orderModel.setSecondBrokerageFee(second);
                orderModel.setDeliveryTime(LocalDateTime.now());
                integralOrderMapper.updateById(orderModel);
                //一级分佣
                UserModel user = userService.getById(orderModel.getUserId());
                user.setIntegral(user.getIntegral() + fist);
                userService.updateById(user);

                //代金券抽成
                //参与分成的券
                Double transactionFeeRatio = inviteConfigModels.get(0).getTransactionFeeRatio();
                Double dividedIntoCoupons = voucher * transactionFeeRatio;
                this.dividedIntoRecordService.dividingByRegionalAgent(user,null, BigDecimal.valueOf(dividedIntoCoupons), orderModel.getOrderSn(), 3);
                //新增积分记录
                IntegralRecordModel integralRecordModel = new IntegralRecordModel();
                integralRecordModel.setName("购买商品返还积分");
                integralRecordModel.setTypeName("返还积分");
                integralRecordModel.setContent("商品【" + orderModel.getGoodsName() + "】收货成功");
                String amountIntegral = String.format("+%.2f分", fist);
                integralRecordModel.setIntegral(amountIntegral);
                integralRecordModel.setUserId(user.getId());
                integralRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
                integralRecordModel.setVoucherType(1);
                integralRecordModel.setVoucherAmount(fist);
                integralRecordMapper.insert(integralRecordModel);
                //二级分佣
                QueryWrapper<InviteRecordModel> inviteRecordQW = new QueryWrapper<>();
                inviteRecordQW.eq("quilt_invite_id", user.getId());
                InviteRecordModel inviteRecordModel = inviteRecordMapper.selectOne(inviteRecordQW);
                if (inviteRecordModel != null && inviteRecordModel.getInviteId() != null) {
                    UserModel inviteUser = userService.getById(inviteRecordModel.getInviteId());//此用户的邀请人对象
                    if (inviteUser != null) {
                        inviteUser.setIntegral(inviteUser.getIntegral() + second);
                        userService.updateById(inviteUser);
                        //新增积分记录
                        IntegralRecordModel integralRecordModel1 = new IntegralRecordModel();
                        integralRecordModel1.setName("粉丝贡献积分(购买商品)");
                        integralRecordModel1.setTypeName("贡献积分(购买商品)");
                        integralRecordModel1.setContent(user.getName() + "购买商品");
                        String amountIntegral1 = String.format("+%.2f分", second);
                        integralRecordModel1.setIntegral(amountIntegral1);
                        integralRecordModel1.setUserId(inviteUser.getId());
                        integralRecordModel1.setCreateTime(CommonHelp.getNowTimestamp());
                        integralRecordMapper.insert(integralRecordModel1);
                    }
                }
                else {
                    //给平台用户发放积分
                    this.adminUserService.accumulatePointsForCurrentPlatformUser(user.getId(),"兑换商品上级分佣积分",BigDecimal.valueOf(second));
                }
                //平台用户添加积分记录
                if(orderModel.getIntegral()>0)
                {
                    this.adminUserService.accumulatePointsForCurrentPlatformUser(user.getId(),"兑换商品平台收回积分",BigDecimal.valueOf(orderModel.getIntegral()));
                }
                //平台用户添加券记录
                if(orderModel.getVoucher()>0)
                {
                    this.adminUserService.accumulatVoucherForCurrentPlatformUser(1,user.getId(),"兑换商品平台收回益联券",BigDecimal.valueOf(orderModel.getVoucher()));
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Result refund(String orderSn, Integer type) {//1仅退款2退货退款
        QueryWrapper<IntegralOrderModel> integralOrderModelQueryWrapper = new QueryWrapper<>();
        integralOrderModelQueryWrapper.eq("order_sn", orderSn);
        IntegralOrderModel orderModel = integralOrderMapper.selectOne(integralOrderModelQueryWrapper);
        if (orderModel != null) {
            if (orderModel.getGoodsId() == null) {
                if (type == 1 && orderModel.getStatus() == 1) {
                    Double integral = orderModel.getIntegral();
                    UserModel userModel = userService.getById(orderModel.getUserId());
                    userModel.setIntegral(userModel.getIntegral() + integral);
                    userService.updateById(userModel);
                    IntegralRecordModel integralRecordModel2 = new IntegralRecordModel();
                    integralRecordModel2.setName("取消订单");
                    integralRecordModel2.setTypeName("返还积分");
                    integralRecordModel2.setContent("积分商品【" + orderModel.getGoodsName() + "】取消订单");
                    String string = "+" + integral + "分";
                    integralRecordModel2.setIntegral(string);
                    integralRecordModel2.setUserId(userModel.getId());
                    integralRecordModel2.setCreateTime(CommonHelp.getNowTimestamp());
                    integralRecordModel2.setVoucherType(1);
                    integralRecordModel2.setVoucherAmount(integral);
                    integralRecordMapper.insert(integralRecordModel2);
                    orderModel.setStatus(6);
                    integralOrderMapper.updateById(orderModel);
                    return Result.success("退还成功");
                } else if (orderModel.getStatus() != 1) {
                    return Result.error(201, "积分商品一经发货不可以退换");
                } else if (type == 2) {
                    return Result.error(201, "积分商品发货之前仅可退还积分，一经发货不可以退换");
                }
            }
            GoodsModel goodsModel = goodsMapper.selectById(orderModel.getGoodsId());
            if (goodsModel != null && goodsModel.getIsRefund() == 1) {
                if (type == 2 && orderModel.getStatus() == 1) {
                    return Result.error(201, "暂未发货，请选择仅退款");
                }
                if (type == 2 && orderModel.getStatus() == 2) {
                    return Result.error(201, "发货中，收货成功后请在1-3个工作日之内申请退货退款");
                }
                if (type == 2 && !canApplyForReturnRefund(orderModel.getDeliveryTime().toLocalDate())) {
                    return Result.error(201, "超过3个工作日，无法申请退款");
                }
                orderModel.setRefundType(type);
                orderModel.setStatus(4);
                integralOrderMapper.updateById(orderModel);
                return Result.success("申请成功");
            } else {
                return Result.error(201, "该商品不允许退款");
            }
        } else {
            return Result.error(201, "该订单不存在");
        }
    }

    public static boolean canApplyForReturnRefund(LocalDate deliveryTime) {
        LocalDate currentDate = LocalDate.now();

        // 计算收货后的天数
        long daysAfterDelivery = ChronoUnit.DAYS.between(deliveryTime, currentDate);

        // 判断是否在1-3个工作日之内
        return daysAfterDelivery >= 0 && daysAfterDelivery <= 3;
    }


    @Override
    public boolean refundReview(String orderSn, Integer status, String refundRemarks) {
        QueryWrapper<IntegralOrderModel> integralOrderModelQueryWrapper = new QueryWrapper<>();
        integralOrderModelQueryWrapper.eq("order_sn", orderSn);
        IntegralOrderModel orderModel = integralOrderMapper.selectOne(integralOrderModelQueryWrapper);
        if (orderModel != null) {
            if (status == 5) {
                orderModel.setStatus(status);
                orderModel.setRefundRemarks(refundRemarks);
                integralOrderMapper.updateById(orderModel);
                return true;
            } else if (status == 6) {
                GoodsModel goodsModel = goodsMapper.selectById(orderModel.getGoodsId());
                if (goodsModel != null && goodsModel.getIsRefund() == 1) {
                    Double firstBrokerageFee = orderModel.getFirstBrokerageFee();
                    UserModel user = userService.getById(orderModel.getUserId());
                    if (firstBrokerageFee != 0) {
                        user.setIntegral(user.getIntegral() - firstBrokerageFee);
                        userService.updateById(user);
                        IntegralRecordModel integralRecordModel2 = new IntegralRecordModel();
                        integralRecordModel2.setName("取消订单");
                        integralRecordModel2.setTypeName("退款");
                        integralRecordModel2.setContent("商品【" + orderModel.getGoodsName() + "】取消订单");
                        String string = "-" + firstBrokerageFee + "分";
                        integralRecordModel2.setIntegral(string);
                        integralRecordModel2.setUserId(user.getId());
                        integralRecordModel2.setCreateTime(CommonHelp.getNowTimestamp());
                        integralRecordModel2.setVoucherType(0);
                        integralRecordModel2.setVoucherAmount(-firstBrokerageFee);
                        integralRecordMapper.insert(integralRecordModel2);
                    }
                    Double secondBrokerageFee = orderModel.getSecondBrokerageFee();
                    if (secondBrokerageFee != 0) {
                        QueryWrapper<InviteRecordModel> inviteRecordQW = new QueryWrapper<>();
                        inviteRecordQW.eq("quilt_invite_id", user.getId());
                        InviteRecordModel inviteRecordModel = inviteRecordMapper.selectOne(inviteRecordQW);
                        if (inviteRecordModel != null && inviteRecordModel.getInviteId() != null) {
                            UserModel inviteUser = userService.getById(inviteRecordModel.getInviteId());//此用户的邀请人对象
                            inviteUser.setIntegral(inviteUser.getIntegral() - secondBrokerageFee);
                            userService.updateById(inviteUser);
                            IntegralRecordModel integralRecordModel1 = new IntegralRecordModel();
                            integralRecordModel1.setName("取消订单");
                            integralRecordModel1.setTypeName("退款");
                            integralRecordModel1.setContent("用户" + user.getPhone() + "取消订单");
                            String string1 = "-" + secondBrokerageFee + "分";
                            integralRecordModel1.setIntegral(string1);
                            integralRecordModel1.setUserId(inviteUser.getId());
                            integralRecordModel1.setVoucherAmount(-secondBrokerageFee);
                            integralRecordModel1.setVoucherType(0);
                            integralRecordModel1.setCreateTime(CommonHelp.getNowTimestamp());
                            integralRecordMapper.insert(integralRecordModel1);
                        }
                    }
                    orderModel.setRefundFirstBrokerageFee(firstBrokerageFee);
                    orderModel.setRefundSecondBrokerageFee(secondBrokerageFee);
                    orderModel.setRefundPrice(orderModel.getVoucher());
                    orderModel.setRefundUseIntegral(orderModel.getIntegral());
                    orderModel.setStatus(status);
                    integralOrderMapper.updateById(orderModel);

                    this.dividedIntoRecordService.RollBackByRegionalAgent("用户取消订单",orderModel.getOrderSn());

                    //返回券和积分
                    UserModel userModel = userService.getById(orderModel.getUserId());
                    userModel.setIntegral(userModel.getIntegral() + orderModel.getIntegral());
                    userModel.setVoucher(userModel.getVoucher() + orderModel.getVoucher());
                    userService.updateById(userModel);
                    //增加券和积分记录
                    //新增积分记录
                    IntegralRecordModel integralRecordModel = new IntegralRecordModel();
                    integralRecordModel.setName("取消订单");
                    integralRecordModel.setTypeName("退款");
                    integralRecordModel.setContent("商品【" + orderModel.getGoodsName() + "】取消订单");
                    String string = "+" + orderModel.getIntegral() + "分";
                    integralRecordModel.setIntegral(string);
                    integralRecordModel.setUserId(userModel.getId());
                    integralRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
                    integralRecordModel.setVoucherType(1);
                    integralRecordModel.setVoucherAmount(orderModel.getIntegral());
                    integralRecordMapper.insert(integralRecordModel);
                    //新增券记录
                    VoucherRecordModel quiltUserVoucherRecord = new VoucherRecordModel();
                    quiltUserVoucherRecord.setName("取消订单");
                    quiltUserVoucherRecord.setTypeName("退款");
                    quiltUserVoucherRecord.setContent("商品【" + orderModel.getGoodsName() + "】取消订单");
                    String amountVoucher = "+" + orderModel.getVoucher() + "券";
                    quiltUserVoucherRecord.setVoucher(amountVoucher);
                    quiltUserVoucherRecord.setUserId(userModel.getId());
                    quiltUserVoucherRecord.setVoucherType(1);
                    quiltUserVoucherRecord.setVoucherAmount(orderModel.getVoucher());
                    quiltUserVoucherRecord.setCreateTime(CommonHelp.getNowTimestamp());
                    voucherRecordMapper.insert(quiltUserVoucherRecord);
                    //消息盒子记录数据
                    MessageBoxModel messageBoxModel = new MessageBoxModel();
                    messageBoxModel.setUserId(userModel.getId());
                    messageBoxModel.setQuiltUserId(userModel.getId());
                    messageBoxModel.setTypeName("退款通知");
                    messageBoxModel.setVoucher(orderModel.getVoucher());
                    messageBoxModel.setNotes("商品【" + orderModel.getGoodsName() + "】取消订单");
                    messageBoxModel.setCreateTime(CommonHelp.getNowTimestamp());
                    messageBoxModel.setOrderSn(orderSn);
                    messageBoxMapper.insert(messageBoxModel);
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 查询积分使用情况
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return {@link Object}
     */
    @Override
    public Object queryStatusPoints(String startTime, String endTime) {

        InviteConfigModel configModel = inviteConfigMapper.selectById(1);

        BigDecimal totalCirculationVoucher=voucherRecordMapper.voucherRecordStatistics(null, startTime, endTime, null, null,null);

        BigDecimal total=totalCirculationVoucher.multiply(BigDecimal.valueOf(configModel.getConversion()));

        //查询签到量和抽奖的量

        BigDecimal count= this.integralOrderMapper.querySumIntegralValues(startTime,endTime);

        Map<String,Object> integralAmountSummary = new HashMap<>();
        integralAmountSummary.put("integralTotal",total.add(count));
        integralAmountSummary.put("integralStock",this.baseMapper.queryUserStatusPoints(startTime,endTime));
        integralAmountSummary.put("pointRedemption",this.baseMapper.queryPointsExchangeAmount(startTime,endTime));


        return integralAmountSummary;
    }

    @Override
    @RedisLockAnnotation(prefix = "cancelOrderOfflineIntegralGoods_", key = "#orderSn")
    public Result cancelOrderOfflineIntegralGoods(String orderSn) {
            QueryWrapper<IntegralOrderModel> integralOrderModelQueryWrapper = new QueryWrapper<>();
            integralOrderModelQueryWrapper.eq("order_sn", orderSn);
            IntegralOrderModel orderModel = integralOrderMapper.selectOne(integralOrderModelQueryWrapper);
            if (orderModel != null) {
                if(orderModel.getGoodsType()==1)
                {
                    return Result.error(201, "非线下核销订单");
                }
                GoodsModel goodsModel = goodsMapper.selectById(orderModel.getGoodsId());
                if(goodsModel==null)
                {
                    return Result.error(201, "商品不存在");
                }
                if (orderModel.getStatus()==7) {

                    orderModel.setStatus(6);
                    integralOrderMapper.updateById(orderModel);

                    //返回券和积分
                    UserModel userModel = userService.getById(orderModel.getUserId());
                    userModel.setIntegral(userModel.getIntegral() + orderModel.getIntegral());
                    userModel.setVoucher(userModel.getVoucher() + orderModel.getVoucher());
                    userService.updateById(userModel);
                    //增加券和积分记录
                    //新增积分记录
                    if(orderModel.getIntegral()>0)
                    {
                        IntegralRecordModel integralRecordModel = new IntegralRecordModel();
                        integralRecordModel.setName("取消订单");
                        integralRecordModel.setTypeName("取消线下兑换商品");
                        integralRecordModel.setContent("商品【" + orderModel.getGoodsName() + "】取消订单");
                        String string = "+" + orderModel.getIntegral() + "分";
                        integralRecordModel.setIntegral(string);
                        integralRecordModel.setUserId(userModel.getId());
                        integralRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
                        integralRecordModel.setVoucherType(1);
                        integralRecordModel.setVoucherAmount(orderModel.getIntegral());
                        integralRecordMapper.insert(integralRecordModel);
                    }
                    if(orderModel.getVoucher()>0)
                    {
                        //新增券记录
                        VoucherRecordModel quiltUserVoucherRecord = new VoucherRecordModel();
                        quiltUserVoucherRecord.setName("取消订单");
                        quiltUserVoucherRecord.setTypeName("取消线下兑换商品");
                        quiltUserVoucherRecord.setContent("商品【" + orderModel.getGoodsName() + "】取消订单");
                        String amountVoucher = "+" + orderModel.getVoucher() + "券";
                        quiltUserVoucherRecord.setVoucher(amountVoucher);
                        quiltUserVoucherRecord.setUserId(userModel.getId());
                        quiltUserVoucherRecord.setVoucherType(1);
                        quiltUserVoucherRecord.setWriteOff(1);
                        quiltUserVoucherRecord.setVoucherAmount(orderModel.getVoucher());
                        quiltUserVoucherRecord.setCreateTime(CommonHelp.getNowTimestamp());
                        voucherRecordMapper.insert(quiltUserVoucherRecord);
                    }

                    //消息盒子记录数据
                    MessageBoxModel messageBoxModel = new MessageBoxModel();
                    messageBoxModel.setUserId(userModel.getId());
                    messageBoxModel.setQuiltUserId(userModel.getId());
                    messageBoxModel.setTypeName("取消通知");
                    messageBoxModel.setVoucher(orderModel.getVoucher());
                    messageBoxModel.setNotes("商品【" + orderModel.getGoodsName() + "】取消订单");
                    messageBoxModel.setCreateTime(CommonHelp.getNowTimestamp());
                    messageBoxModel.setOrderSn(orderSn);
                    messageBoxMapper.insert(messageBoxModel);
                    return Result.success("取消成功");
                }
                else if(orderModel.getStatus()==6) {
                    return Result.error(201, "已取消");
                }
        }
            return Result.error(201,"订单不存在");
    }


    /**
     * 核销积分商城订单
     *
     * @param integralOrderModel 积分阶模型
     * @param writeoffUser       注销用户
     * @return {@link Result}
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @RedisLockAnnotation(prefix = "writeOffIntegralOrder_", key = "#orderSn")
    public Result writeOffIntegralOrder(IntegralOrderModel integralOrderModel,UserModel writeoffUser){
        String code=null;
        if(StrUtil.isNotBlank(integralOrderModel.getCode()))
        {
            code=integralOrderModel.getCode().replaceAll("goods=2#","");
        }else{
            return Result.error(201,"请重新扫码");
        }
        //第一步，判断这个订单
        IntegralOrderModel orderModel = integralOrderMapper.queryIntegralOrderByCode(code);
        if(orderModel==null){
            return Result.error(201,"订单不存在");
        }
        if(orderModel.getStatus()!=7)
        {
            return Result.error(201,"订单已核销");
        }
        //判断是否为商家订单
        if(orderModel.getBusinessId()!=null&&orderModel.getBusinessUserid()!=null)
        {
            if(!writeoffUser.getId().equals(orderModel.getBusinessUserid()))
            {

                return Result.error(201,"需指定商家扫码核销");
            }
        }else{
            Wrapper<AdminUserModel> whetherThereIsAProxyUserWhoChangesMobilePhoneNumber = new QueryWrapper<AdminUserModel>()
                    .eq("phone", writeoffUser.getPhone())
                    .eq("role_id",4);
            if(this.adminUserService.count(whetherThereIsAProxyUserWhoChangesMobilePhoneNumber)==0)
            {
                return Result.error(201,"需赋能店区代扫码核销");
            }
        }

        List<InviteConfigModel> inviteConfigModels = inviteConfigMapper.selectList(null);
        //手续费比例
        Double transactionFeeRatio = inviteConfigModels.get(0).getTransactionFeeRatio();
        //手续费
        double handlingFees = orderModel.getVoucher() * transactionFeeRatio;
        //谁收券抽谁的
        BigDecimal newTransferAmount = BigDecimal.valueOf(orderModel.getVoucher()).subtract(BigDecimal.valueOf(handlingFees));
        orderModel.setStatus(3);
        if (orderModel.getVoucher()>0){
            //获取返佣比例
            Double brokerage = inviteConfigModels.get(0).getBrokerage();
            Double brokerageTwo = inviteConfigModels.get(0).getBrokerageTwo();
            orderModel.setBrokerage(brokerage);
            orderModel.setBrokerageTwo(brokerageTwo);
            //分佣积分
            Double voucher = orderModel.getVoucher();//消费的券
            double v = voucher * inviteConfigModels.get(0).getConversion();//根据比例转换的积分
            double fist = v * brokerage;
            double second = v * brokerageTwo;
            orderModel.setFirstBrokerageFee(fist);
            orderModel.setSecondBrokerageFee(second);
            orderModel.setDeliveryTime(LocalDateTime.now());
            integralOrderMapper.updateById(orderModel);
            UserModel user = userService.getById(orderModel.getUserId());
            //一级分佣
            if(fist>0)
            {
                user.setIntegral(user.getIntegral() + fist);
                userService.updateById(user);
            }
            if(voucher>0)
            {
                writeoffUser.setVoucher(writeoffUser.getVoucher() + orderModel.getVoucher() - handlingFees);
                userService.updateById(writeoffUser);
            }
            //代金券抽成
            //参与分成的券
            Double dividedIntoCoupons = voucher * transactionFeeRatio;
            this.dividedIntoRecordService.dividingByRegionalAgent(user,null, BigDecimal.valueOf(dividedIntoCoupons), orderModel.getOrderSn(), 3);
            //新增积分记录
            IntegralRecordModel integralRecordModel = new IntegralRecordModel();
            integralRecordModel.setName("购买商品返还积分");
            integralRecordModel.setTypeName("返还积分");
            integralRecordModel.setContent("商品【" + orderModel.getGoodsName() + "】兑换成功");
            String amountIntegral = String.format("+%.2f分", fist);
            integralRecordModel.setIntegral(amountIntegral);
            integralRecordModel.setUserId(user.getId());
            integralRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
            integralRecordModel.setVoucherType(1);
            integralRecordModel.setVoucherAmount(fist);
            integralRecordMapper.insert(integralRecordModel);
            //二级分佣
            QueryWrapper<InviteRecordModel> inviteRecordQW = new QueryWrapper<>();
            inviteRecordQW.eq("quilt_invite_id", user.getId());
            InviteRecordModel inviteRecordModel = inviteRecordMapper.selectOne(inviteRecordQW);
            if (inviteRecordModel != null && inviteRecordModel.getInviteId() != null) {
                UserModel inviteUser = userService.getById(inviteRecordModel.getInviteId());//此用户的邀请人对象
                if (inviteUser != null) {
                    inviteUser.setIntegral(inviteUser.getIntegral() + second);
                    userService.updateById(inviteUser);
                    //新增积分记录
                    IntegralRecordModel integralRecordModel1 = new IntegralRecordModel();
                    integralRecordModel1.setName("粉丝贡献积分(购买商品)");
                    integralRecordModel1.setTypeName("贡献积分(购买商品)");
                    integralRecordModel1.setContent(user.getName() + "购买商品");
                    String amountIntegral1 = String.format("+%.2f分", second);
                    integralRecordModel1.setIntegral(amountIntegral1);
                    integralRecordModel1.setUserId(inviteUser.getId());
                    integralRecordModel1.setCreateTime(CommonHelp.getNowTimestamp());
                    integralRecordMapper.insert(integralRecordModel1);
                }
            } else {
                //给平台用户发放积分
                this.adminUserService.accumulatePointsForCurrentPlatformUser(user.getId(),"兑换商品上级分佣积分",BigDecimal.valueOf(second));
            }
            adminUserService.accumulatePointsForCurrentPlatformUser(writeoffUser.getId(),"积分商品线下核销",BigDecimal.valueOf(orderModel.getIntegral()));
            Integer buniessId = orderModel.getBusinessId();
            if(orderModel.getVoucher()>0)
            {
                QueryWrapper<VoucherRecordModel> voucherRecordModelQueryWrapper=new QueryWrapper<>();
                voucherRecordModelQueryWrapper.eq("order_id",orderModel.getOrderSn());
                voucherRecordModelQueryWrapper.eq("user_id",orderModel.getUserId());
                voucherRecordModelQueryWrapper.eq("write_off",2);
                VoucherRecordModel voucherRecordModel=voucherRecordMapper.selectOne(voucherRecordModelQueryWrapper);
                if(voucherRecordModel!=null) {
                    voucherRecordModel.setWriteOff(1);
                    voucherRecordMapper.updateById(voucherRecordModel);
                }
            }


            if (buniessId != null){
                if(orderModel.getVoucher()>0)
                {
                    //增加益联券记录
                    VoucherRecordModel voucherRecordModel = new VoucherRecordModel();
                    voucherRecordModel.setName("兑换商品成功");
                    voucherRecordModel.setTypeName("商家线下核销");
                    String amountVoucher = "+" + newTransferAmount.doubleValue() + "券";
                    voucherRecordModel.setVoucher(amountVoucher);
                    voucherRecordModel.setUserId(writeoffUser.getId());
                    voucherRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
                    voucherRecordModel.setVoucherType(1);
                    voucherRecordModel.setVoucherAmount(newTransferAmount.doubleValue());
                    voucherRecordModel.setWriteOff(1);
                    voucherRecordMapper.insert(voucherRecordModel);
                }
            }else {

                if(orderModel.getVoucher()>0)
                {
                    //增加益联券记录
                    VoucherRecordModel voucherRecordModel = new VoucherRecordModel();
                    voucherRecordModel.setName("兑换商品成功");
                    voucherRecordModel.setTypeName("赋能店线下核销");
                    String amountVoucher = "+" + newTransferAmount.doubleValue() + "券";
                    voucherRecordModel.setVoucher(amountVoucher);
                    voucherRecordModel.setUserId(writeoffUser.getId());
                    voucherRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
                    voucherRecordModel.setVoucherType(1);
                    voucherRecordModel.setVoucherAmount(newTransferAmount.doubleValue());
                    voucherRecordModel.setWriteOff(1);
                    voucherRecordMapper.insert(voucherRecordModel);
                }
            }
        }
        return Result.success("核销成功");
    }
}
